package com.cabrida.livestar.login;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jpush.android.api.JPushInterface;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.forgetpassword.ForgetPasswordActivity;
import com.cabrida.livestar.main.MainActivity;
import com.cabrida.livestar.mainstar.MainStarActivity;
import com.cabrida.livestar.model.WeiXinQQUserInfo;
import com.cabrida.livestar.register.RegisterActivity;
import com.cabrida.livestar.util.ComAnalysis;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.util.StringUtils;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
/**
 * 登录
 */
public class LoginActivity extends BaseActivity {
	public static final String TAG = LoginActivity.class.getSimpleName();
	private RelativeLayout rl_all;
	private TextView tv_versions;
	private TextView tv_register;
	private Button btn_login;
	private EditText et_mobile;
	private EditText et_psw;
	private TextView tv_forget_password;
	private LinearLayout ll_apply;
	private TextView tv_apply_live;
	private ImageButton ib_close;
	private ImageButton ib_tel;
	private ImageView iv_qq;
	
	private final String APP_ID = "1106059551";
	private Tencent mTencent;
	private String tmpOpenid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_login);
		rl_all = (RelativeLayout) findViewById(R.id.rl_all);
		tv_versions = (TextView) findViewById(R.id.tv_versions);
		tv_register = (TextView) findViewById(R.id.tv_register);
		btn_login = (Button) findViewById(R.id.btn_login);
		et_mobile = (EditText) findViewById(R.id.et_mobile);
		et_psw = (EditText) findViewById(R.id.et_psw);
		tv_forget_password = (TextView) findViewById(R.id.tv_forget_password);
		tv_apply_live = (TextView) findViewById(R.id.tv_apply_live);
		ll_apply = (LinearLayout) findViewById(R.id.ll_apply);
		ib_close = (ImageButton) findViewById(R.id.ib_close);
		ib_tel = (ImageButton) findViewById(R.id.ib_tel);
		iv_qq = (ImageView) findViewById(R.id.iv_qq);

//		et_mobile.setText("13800138003");
//		et_psw.setText("123456");
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		rl_all.setOnClickListener(this);
		tv_register.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		tv_forget_password.setOnClickListener(this);
		tv_apply_live.setOnClickListener(this);
		ib_close.setOnClickListener(this);
		ib_tel.setOnClickListener(this);
		iv_qq.setOnClickListener(this);
		
		tv_versions.setText(Urls.SERVERS_VERSIONS);
	}
	
	
	/**
	 * QQ登录按钮 点击事件
	 */
	private void btn_login_qq_click() {
//		mTencent = Tencent.createInstance(APP_ID, this.getApplicationContext());
//        if (!mTencent.isSessionValid())
//        {
//            mTencent.login(this, "all", new BaseUiListener());
//        }
	}
	
	/**
	 * 当自定义的监听器实现IUiListener接口后，必须要实现接口的三个方法， onComplete onCancel onError
	 * 分别表示第三方登录成功，取消 ，错误。
	 */
	private class BaseUiListener implements IUiListener {
		public void onCancel() {
			// TODO Auto-generated method stub
		}

		public void onComplete(Object response) {
			// TODO Auto-generated method stub
			showToast("授权成功");
			try {
				// 获得的数据是JSON格式的，获得你想获得的内容
				// 如果你不知道你能获得什么，看一下下面的LOG
				tmpOpenid = ((JSONObject) response).getString("openid");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/**
			 * 到此已经获得OpneID以及其他你想获得的内容了
			 * QQ登录成功了，我们还想获取一些QQ的基本信息，比如昵称，头像什么的，这个时候怎么办？
			 * sdk给我们提供了一个类UserInfo，这个类中封装了QQ用户的一些信息，我么可以通过这个类拿到这些信息
			 * 如何得到这个UserInfo类呢？
			 */
			QQToken qqToken = mTencent.getQQToken();
			UserInfo info = new UserInfo(getApplicationContext(), qqToken);
			// 这样我们就拿到这个类了，之后的操作就跟上面的一样了，同样是解析JSON
			info.getUserInfo(new IUiListener() {
				public void onComplete(final Object response) {
					parseUserInfo(response.toString(),"10");
				}

				public void onCancel() {

				}

				public void onError(UiError arg0) {

				}
			});
		}

		public void onError(UiError arg0) {
		}
	}
	WeiXinQQUserInfo weiXinUserInfo;
	private void parseUserInfo(String string,String source) {
		try {
			weiXinUserInfo = new WeiXinQQUserInfo();
			JSONObject object = new JSONObject(string);
			weiXinUserInfo.setOpenid(tmpOpenid);
			weiXinUserInfo.setNickname(object.getString("nickname"));
			weiXinUserInfo.setGender(object.getString("gender"));
			weiXinUserInfo.setProvince(object.getString("province"));
			weiXinUserInfo.setCity(object.getString("city"));
			weiXinUserInfo.setHeadimgurl(object.getString("figureurl_qq_2"));
			getLoginOtherData(source);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 第三方登录微信 20 QQ 10
	 */
	private void getLoginOtherData(String source) {
		RequestParams params = new RequestParams();
		params.put("openid", weiXinUserInfo.getOpenid());
		params.put("source", source);
		params.put("name", weiXinUserInfo.getNickname());
		params.put("icon", weiXinUserInfo.getHeadimgurl());
		params.put("gender", weiXinUserInfo.getGender());
		params.put("country", weiXinUserInfo.getCountry());
		params.put("province", weiXinUserInfo.getProvince());
		params.put("city", weiXinUserInfo.getCity());

		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.USER_REGISTOTHER_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "login_response", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);

						if (code == HttpHelp.Succeed) {
							ComAnalysis.analysisJSONUser(context,response);
							 if (Global.U_type.equals(Global.USER_TYPE_STAR))
							 {
							 openActivity(MainStarActivity.class);
							 }else {
							 openActivity(MainActivity.class);
							 }
							finish();

						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	/**
	 * 登录按钮 点击事件
	 */
	private void btn_login_click() {
		String str_mobile = et_mobile.getText().toString().trim();
		String str_password = et_psw.getText().toString().trim();

		if (TextUtils.isEmpty(str_mobile)) {
			showToast("请填写手机号");
			return;
		}
		if (!StringUtils.isPhone(str_mobile)) {
			showToast("请输入正确的手机号");
			return;
		}

		if (TextUtils.isEmpty(str_password)) {
			showToast("请填写密码");
			return;
		}
		getLoginData(str_mobile, str_password);
	}

	private void getLoginData(String str_mobile, String str_password) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("phone", str_mobile);
		params.put("password", str_password);
		
		String rid = JPushInterface.getRegistrationID(getApplicationContext());
		params.put("device", rid);
		params.put("type", "20");

		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.USER_LOGIN_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "login_response", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);

						if (code == HttpHelp.Succeed) {
							ComAnalysis.analysisJSONUser(context,response);
						
							 if (Global.U_type.equals(Global.USER_TYPE_STAR))
							 {
							 openActivity(MainStarActivity.class);
							 }else {
							 openActivity(MainActivity.class);
							 }
							finish();

						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.tv_register:
			this.finish();
			openActivity(RegisterActivity.class);
			break;
		case R.id.tv_apply_live:
			ll_apply.setVisibility(View.VISIBLE);
			break;
		case R.id.ib_close:
			ll_apply.setVisibility(View.GONE);
			break;
		case R.id.ib_tel:
			
			break;
		case R.id.tv_forget_password:
			this.finish();
			openActivity(ForgetPasswordActivity.class);
			break;
		case R.id.btn_login:
			btn_login_click();
			break;
		case R.id.iv_qq:
			btn_login_qq_click();
			break;

		default:
			break;
		}
	}

}
